package com.sgcc.operate.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.exception.CustomException;
import com.sgcc.common.core.utils.SecurityUtils;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.operate.domain.OIndiForm;
import com.sgcc.operate.mapper.OIndiFormMapper;
import com.sgcc.system.api.RemoteDictDataService;
import com.sgcc.system.api.RemoteUserService;
import com.sgcc.system.api.domain.SysUser;
import com.sgcc.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sgcc.operate.mapper.OIndiDefiMapper;
import com.sgcc.operate.domain.OIndiDefi;
import com.sgcc.operate.service.IOIndiDefiService;
import org.springframework.util.CollectionUtils;

/**
 * 运营指标定义Service业务层处理
 *
 * @author sgcc
 * @date 2021-03-23
 */
@Service
public class OIndiDefiServiceImpl implements IOIndiDefiService {
    @Autowired
    private OIndiDefiMapper oIndiDefiMapper;
    @Autowired
    private OIndiFormMapper oIndiFormMapper;
    @Autowired
    private RemoteDictDataService remoteDictDataService;
    @Autowired
    private TokenService tokenService;

    private static final Logger log = LoggerFactory.getLogger(OIndiDefiServiceImpl.class);
    /**
     * 查询运营指标定义
     *
     * @param id 运营指标定义ID
     * @return 运营指标定义
     */
    @Override
    public OIndiDefi selectOIndiDefiById(String id) {
        return oIndiDefiMapper.selectOIndiDefiById(id);
    }

    /**
     * 查询运营指标定义列表
     *
     * @param oIndiDefi 运营指标定义
     * @return 运营指标定义
     */
    @Override
    public List<OIndiDefi> selectOIndiDefiList(OIndiDefi oIndiDefi) {
        return oIndiDefiMapper.selectOIndiDefiList(oIndiDefi);
    }

    /**
     * 新增运营指标定义
     *
     * @param oIndiDefi 运营指标定义
     * @return 结果
     */
    @Override
    public int insertOIndiDefi(OIndiDefi oIndiDefi) {
        LoginUser loginUser = tokenService.getLoginUser();
        oIndiDefi.setCreateDate(new Date());
        oIndiDefi.setUpdateDate(new Date());
        oIndiDefi.setCreateBy(loginUser.getUserid());
        oIndiDefi.setUpdateBy(loginUser.getUserid());
        oIndiDefi.setModifyorg(loginUser.getSysUser().getDeptId());
        oIndiDefi.setDelFlag("0");
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        oIndiDefi.setId(id);
        R idstr = remoteDictDataService.getIdStr("same_day_id_create", "o_indi_no");
        if (idstr.getCode() == 200) {
            oIndiDefi.setIndino("ZBDY" + idstr.getData());
            return oIndiDefiMapper.insertOIndiDefi(oIndiDefi);
        } else {
            return 0;
        }
    }

    /**
     * 修改运营指标定义
     *
     * @param oIndiDefi 运营指标定义
     * @return 结果
     */
    @Override
    public int updateOIndiDefi(OIndiDefi oIndiDefi) {
        return oIndiDefiMapper.updateOIndiDefi(oIndiDefi);
    }

    /**
     * 批量删除运营指标定义
     *
     * @param ids 需要删除的运营指标定义ID
     * @return 结果
     */
    @Override
    public String deleteOIndiDefiByIds(String[] ids) {
        List<String> list = new ArrayList<String>();
        List<String> idList= CollectionUtils.arrayToList(ids);
        for (String id : idList){
            OIndiForm oIndiForm = new OIndiForm();
            oIndiForm.setIndiid(id);
            List<OIndiForm> oIndiForms = oIndiFormMapper.selectOIndiFormList(oIndiForm);
            if (oIndiForms.size() > 0){
                list.add(id);
            }
        }
        if (list.size() > 0){
            // 查询出所有被引用的指标的详细信息
            List<OIndiDefi> oIndiDefiList = oIndiDefiMapper.selectOIndiDefiByIds(list);
            String indiname = "";
            int count = 0;
            for (OIndiDefi oIndiDefi : oIndiDefiList){
                if (count == 0){
                    indiname += oIndiDefi.getIndiname();
                }else {
                    indiname += ","+oIndiDefi.getIndiname();
                }
                count++;
            }
            return "指标名称："+indiname+"已被引用，无法删除！";
        }else {
            int i = oIndiDefiMapper.deleteOIndiDefiByIds(ids);
            return i+"";
        }
    }

    /**
     * 删除运营指标定义信息
     *
     * @param id 运营指标定义ID
     * @return 结果
     */
    @Override
    public int deleteOIndiDefiById(String id) {
        return oIndiDefiMapper.deleteOIndiDefiById(id);
    }


    @Override
    public String importIndiDefi(List<OIndiDefi> indiDefiList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(indiDefiList) || indiDefiList.size() == 0) {
            throw new CustomException("导入运营指标不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (OIndiDefi indiDefi : indiDefiList) {
            try {
                // 验证是否存在这个用户
                OIndiDefi oIndiDefi = oIndiDefiMapper.selectOIndiDefiByIndino(indiDefi.getIndino());
                if (StringUtils.isNull(oIndiDefi)) {

                    insertOIndiDefi(indiDefi);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、指标名称名称 " + indiDefi.getIndiname() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、指标名称名称 " + indiDefi.getIndiname() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、指标名称名称 " + indiDefi.getIndiname() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
